﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;

using System.Text;

using System.Net;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Runtime.InteropServices;
using TrenitaliaWP7.Resources;
using Microsoft.Phone.Info;

namespace TrenitaliaWP7
{
    class Utilities
    {
        public static String computeUrl(String from, string to, int day, int month, int year, int hour, int minute)
        {
            /*http://orario.trenitalia.com/b2c/nppPriceTravelSolutions.do?car=0&stazin=
             * treviso
             * &stazout=
             * marghera
             * &datag=
             * 10
             * &datam=
             * 08
             * &dataa=
             * 2010
             * &timsh=
             * 11
             * &stazin_r=Staz_DA&stazout_r=Staz_A&timsm=
             * 40
             * &timsm_r=
             * 40
             * &lang=it&nreq=5&channel=tcom&npag=1&lang_r=it&nreq_r=5&channel_r=tcom&npag_r=1&x=23&y=4
            
            */
            var query =
                "http://orario.trenitalia.com/b2c/nppPriceTravelSolutions.do?car=0&stazin=" +
                from +
                "&stazout=" +
                to +
                "&datag=" +
                day +
                "&datam=" +
                month +
                "&dataa=" +
                year +
                "&timsh=" +
                hour +
                "&stazin_r=Staz_DA&stazout_r=Staz_A&timsm=" +
                minute +
                "&timsm_r=" +
                minute +
                "&lang=" + Strings.URL_Lang +
                //"&lang=it" +
                "&nreq=5&channel=tcom&npag=1" +
                "&lang_r=" + Strings.URL_Lang +
                "&nreq_r=5&channel_r=tcom&npag_r=1&x=23&y=4";
            //2012-05-27 -> http://www.lefrecce.it/B2CWeb/searchExternal.do?parameter=initBaseSearch&isRoundTrip=false&departureStation=Treviso+Centrale&arrivalStation=Venezia+%28+Tutte+Le+Stazioni+%29&departureDate=27-05-2012&departureTime=9&returnDate=&returnTime=9&noOfAdults=1&noOfChildren=0&ynFlexibleDates=0&x=57&y=5&pageNumber=0&fromBaseOrAdvanceSearch=baseSearch&ynFlexibleDates=off
            /*query = "http://www.lefrecce.it/B2CWeb/searchExternal.do?parameter=initBaseSearch&isRoundTrip=false&departureStation=" +
                from +
                "&arrivalStation=" +
                to +
                "&departureDate=" +
                day + "-" + (month < 10 ? "0" + month : "" + month) + "-" + year +// 27-05-2012"+
                "&departureTime=" +
                "9" +
                "&returnDate=&returnTime=" +
                "9" +
                "&noOfAdults=1&noOfChildren=0&ynFlexibleDates=0&x=57&y=5&" +
                "pageNumber=" +
                "0" +
                "&fromBaseOrAdvanceSearch=baseSearch&ynFlexibleDates=off";
            */
            return query;
        }

        public static String computeBuyUrl(String from, string to, int day, int month, int year, int hour, int minute)
        {

            /*

             &timsh=15&00&nreq_r=5&npag=1&sort=0&economy=0&det=6
             * 
             * */
            var query =
                "http://orario.trenitalia.com/b2c/nppTravelChoice.do?lang=" +
                //"it" +
                Strings.URL_Lang +
                "&stazin=" +
                from +
                "&stazout=" +
                to +
                "&datag=" +
                day +
                "&datam=" +
                month +
                "&dataa=" +
                year +
                "&timsh=" +
                hour +
                "&timsm=" +
                minute +
                "&timsm_r=" +
                minute +
                "&nreq_r=5&npag=1&sort=0";
            //"&economy=0"+
            //"&det=";

            /*
            var query = "http://orario.trenitalia.com/b2c/nppTravelChoice.do?lang=it&stazin=" +
                "treviso" + 
                "&stazout=" + 
                "marghera" + 
                "&datag=" +
                "18" + 
                "&datam="+
                "04" + 
                "&dataa=" +
                "2011" + 
                "&timsh=" +
                "16" + 
                "&timsm=" + 
                "24" + 
                "&timsm_r=" + 
                "24" + 
                "&nreq_r=5&npag=1&sort=0&economy=0&det=";
            */

            return query;
        }


        public static string ComputeDetailsUrl(string number)
        {
            return "http://mobile.viaggiatreno.it/viaggiatreno/mobile/scheda?dettaglio=visualizza&numeroTreno=" + number;
        }
        public static string ComputeDelayUrl(string number)
        {
            // http://mobile.trenitalia.com/%28S%28percoh55ylgk43203f20qp2r%29%29/W2/ViaggiaTrenoXHTML.aspx?__VIEWSTATE=%2FwEPDwUINzkxNzIxNzFkZPFqhgz5UtViWt7bQP3v3teH1nQI&__EVENTVALIDATION=%2FwEWAwK5%2Bb6XCALzlKGwCgK28MDdBY68r228gLfuMtHP4OfARfQddthh&Text1=11117&butt_Find=Cerca
            //return "http://mobile.trenitalia.com/%28S%28percoh55ylgk43203f20qp2r%29%29/W2/ViaggiaTrenoXHTML.aspx?__VIEWSTATE=%2FwEPDwUINzkxNzIxNzFkZPFqhgz5UtViWt7bQP3v3teH1nQI&__EVENTVALIDATION=%2FwEWAwK5%2Bb6XCALzlKGwCgK28MDdBY68r228gLfuMtHP4OfARfQddthh&Text1=" + number + "&butt_Find=Cerca";

            //return "http://mobile.trenitalia.com/(S(g3zj0qfluaxloofmrjx0jga1))/W2/ViaggiaTrenoXHTML.aspx?__VIEWSTATE=%2FwEPDwUINzkxNzIxNzFkZJpueSXW59bOZXVLPMcXIISh8QIH&__EVENTVALIDATION=%2FwEWAwKTwOytDgLzlKGwCgK28MDdBSzpF8svKzJ5SeANvr6V%2BE2kU96W&Text1=" + number + "&butt_Find=Cerca";

            return "http://mobile.trenitalia.com/(S(3sizfzml1ftdmc45fzibl4ur))/W2/ViaggiaTrenoXHTML.aspx?__VIEWSTATE=%2FwEPDwUINzkxNzIxNzEPZBYCAgMPZBYCAgcPDxYEHgRUZXh0BS5TZXJ2aXppbyBub24gZGlzcG9uaWJpbGUsIFJpcHJvdmFyZSBwacO5IHRhcmRpHgdWaXNpYmxlZ2RkZLbOSTwxDILHjNu%2BycRyzEBv%2FjaV&__EVENTVALIDATION=%2FwEWAwLp795sAvOUobAKArbwwN0FpI1%2B1SRJLQ6QeAVOTXbDbjsjIX8%3D&Text1=" + number + "&butt_Find=Cerca";
        }

        public static void getHTML(string query, string options, Action<string> callback, Action<string, string> callback2, Action error)
        {
            try
            {
                HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(query);
                req.Method = "GET";
                req.BeginGetResponse(
                    (asyncResult) =>
                    {
                        try
                        {
                            HttpWebResponse objResponse = null;
                            StreamReader objs = null;

                            HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;

                            objResponse = (HttpWebResponse)request.EndGetResponse(asyncResult);
                            objs = new StreamReader(objResponse.GetResponseStream());

                            var s = objs.ReadToEnd();
                            if (callback2 != null)
                                callback2(s, options);
                            else if (callback != null)
                                callback(s);

                            return;
                            //HttpWebRequest requ = (HttpWebRequest)HttpWebRequest.Create(query);
                            //requ.Method = "GET";
                            //requ.BeginGetResponse(
                            //    (asyncResult2) =>
                            //    {
                            //        HttpWebRequest request2 = (HttpWebRequest)asyncResult2.AsyncState;

                            //        var objResponse2 = (HttpWebResponse)request2.EndGetResponse(asyncResult2);
                            //        var objs2 = new StreamReader(objResponse2.GetResponseStream());
                            //var s = objs.ReadToEnd();
                            //callback(s);
                            //    }
                            //    , requ);
                            //return;
                        }
                        catch (ArgumentOutOfRangeException e)
                        {
                            e.ToString();
                        }
                        catch (Exception e)
                        {
                            e.ToString();
                            error();
                        }
                    }
                    , req);
            }
            catch (Exception e)
            {
                e.ToString();
                error();
            }
        }
        public static void getHTML(string query, Action<string> callback, Action error)
        {
            getHTML(query, "", callback, null, error);
            //try
            //{
            //    HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(query);
            //    req.Method = "GET";
            //    req.BeginGetResponse(
            //        (asyncResult) =>
            //        {
            //            try
            //            {
            //                HttpWebResponse objResponse = null;
            //                StreamReader objs = null;

            //                HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;

            //                objResponse = (HttpWebResponse)request.EndGetResponse(asyncResult);
            //                objs = new StreamReader(objResponse.GetResponseStream());

            //                HttpWebRequest requ = (HttpWebRequest)HttpWebRequest.Create(query);
            //                requ.Method = "GET";
            //                requ.BeginGetResponse(
            //                    (asyncResult2) =>
            //                    {
            //                        HttpWebRequest request2 = (HttpWebRequest)asyncResult2.AsyncState;

            //                        var objResponse2 = (HttpWebResponse)request2.EndGetResponse(asyncResult2);
            //                        var objs2 = new StreamReader(objResponse2.GetResponseStream());
            //                        var s = objs2.ReadToEnd();
            //                        callback(s);
            //                    }
            //                    , requ);
            //                return;
            //            }
            //            catch (Exception)
            //            {
            //                error();
            //            }
            //        }
            //        , req);
            //}
            //catch (Exception)
            //{
            //    error();
            //}
        }


        public static void getHTML(string query, string options, Action<string, string> callback, Action error)
        {
            getHTML(query, options, null, callback, error);
            //try
            //{
            //    HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(query);
            //    req.Method = "GET";
            //    req.BeginGetResponse(
            //        (asyncResult) =>
            //        {
            //            try
            //            {
            //                HttpWebResponse objResponse = null;
            //                StreamReader objs = null;

            //                HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;

            //                objResponse = (HttpWebResponse)request.EndGetResponse(asyncResult);
            //                objs = new StreamReader(objResponse.GetResponseStream());

            //                HttpWebRequest requ = (HttpWebRequest)HttpWebRequest.Create(query);
            //                requ.Method = "GET";
            //                requ.BeginGetResponse(
            //                    (asyncResult2) =>
            //                    {
            //                        HttpWebRequest request2 = (HttpWebRequest)asyncResult2.AsyncState;

            //                        var objResponse2 = (HttpWebResponse)request2.EndGetResponse(asyncResult2);
            //                        var objs2 = new StreamReader(objResponse2.GetResponseStream());
            //                        var s = objs2.ReadToEnd();
            //                        callback(s, options);
            //                    }
            //                    , requ);
            //                return;
            //            }
            //            catch (Exception)
            //            {
            //                error();
            //            }
            //        }
            //        , req);
            //}
            //catch (Exception)
            //{
            //    error();
            //}
        }

        public static string GetUtilizationUrl(bool isTrial)
        {
            return GetUtilizationUrl(0, isTrial);
        }

        public static string GetUtilizationUrl(int occ, bool isTrial)
        {

            var s = "http://fboscari.altervista.org/submit_Utilizzi.php?name=" +
                Strings.AppTitle +
                (isTrial ? " Trial" : "") +
                "&id=" +
                getID();
            if (occ >= 1)
                s += "&occ=" +
                    occ;
            return s;

        }
        public static string getID()
        {
            byte[] result = null;
            object uniqueId;
            if (DeviceExtendedProperties.TryGetValue("DeviceUniqueId", out uniqueId))
                result = (byte[])uniqueId;
            var s = "";
            for (int i = 0; i < result.Length; i++)
                s += result[i];
            return s;
        }
    }
}
